#include <robot.hxx>
#include <myfilelog.hxx>
#include <loghelper.hxx>
#include <windows.h>
#include "micro.hxx"
#include "robotmanager.hxx"
#include "task.hxx"

using namespace std;

Robot::Robot(RobotManager* robotManager, bool isStanding, FileLog* filelog)
: robotManager(robotManager),
isStanding(isStanding),
isShutdownRequested(false),
_filelog(filelog)
{
	Start();
}

void Robot::Execute(Thread::Arg arg)
{
	const int MaxFailedCount = 6000;

	LOGINFO("Robot #"<<RealThreadId()<<" started...");

	int failedCount = 0;
	Task* task = NULL;
	while (!isShutdownRequested)
	{
		task = robotManager->GetReadyTask();
		if (task == NULL)
		{
			if (--failedCount == 0)
				Shutdown();

			Thread::Yield();
			continue;
		}

		failedCount = MaxFailedCount;

		task->Execute();
	}

	LOGINFO("Robot #"<<RealThreadId()<<" ended.");
}

void Robot::Shutdown(void)
{
	isShutdownRequested = true;
}